package com.gzhryc.shared_device.oem.micro.iot.jetty;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.servlet.AbsHttpServlet;
import com.gzhryc.servlet.HttpHandler;
import com.gzhryc.servlet.HttpHandlerFactory;
import com.gzhryc.servlet.Resource;
import com.gzhryc.servlet.WebUtils;

public class MainServlet extends AbsHttpServlet {

	private static final long serialVersionUID = 1L;

	final static Logger log = Logger.getLogger(MainServlet.class);

	HttpHandler httpHandler;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.httpHandler = HttpHandlerFactory.readHttpHandler("com.gzhryc.shared_device.oem.micro.iot.controllers");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			Object uri = req.getAttribute("uri");
			if(uri != null) {
				Resource resource = HttpHandlerFactory.execute(httpHandler, uri.toString(), req, resp, fileItemFactory);
				if (resource != null) {
					resource.export(req, resp);
				} else {
					log.warn("请求未处理，uri = " + uri);
				}
			}else{
				log.error("未进行解析的访问路径：" + WebUtils.getRequestURI(req));
			}
		} catch (Exception e) {
			log.error("请求处理错误", e);
		} finally {
			JdbcSession.clear();
		}
	}
}
